package com.njtoyo.taxi.admin.service.business.advertise.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.cache.PrimaryCachePutter;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.mapper.master.entity.*;
import com.njtoyo.taxi.admin.mapper.master.enums.AdvertiseApp;
import com.njtoyo.taxi.admin.mapper.master.enums.AdvertiseCategory;
import com.njtoyo.taxi.admin.mapper.master.enums.AdvertiseLocation;
import com.njtoyo.taxi.admin.mapper.master.enums.DriverRegionServiceArrangementCategory;
import com.njtoyo.taxi.admin.mapper.master.mapper.*;
import com.njtoyo.taxi.admin.mongo.entity.primary.AdvertiseSinglePicResourceMongo;
import com.njtoyo.taxi.admin.mongo.repository.primary.AdvertiseSinglePicResourceRepository;
import com.njtoyo.taxi.admin.rest.presenter.business.advertise.AdvertiseDetailsPresenter;
import com.njtoyo.taxi.admin.rest.presenter.business.advertise.AdvertisePagePresenter;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.admin.rest.wrapper.business.advertise.*;
import com.njtoyo.taxi.admin.service.business.advertise.AdvertiseService;
import com.njtoyo.taxi.admin.utils.OssClient;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.njtoyo.taxi.entity.backend.Enum;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static java.util.stream.Collectors.toList;

@Service
@Slf4j
@DS(Const.PRIMARY_DS)
public class AdvertiseServiceImpl implements AdvertiseService {
    @Autowired
    private AdvertiseMapper advertiseMapper;
    @Autowired
    private GeoCantonMapper geoCantonMapper;
    @Autowired
    private GeoAreaMapper geoAreaMapper;
    @Autowired
    private GeoCantonAreaMapper geoCantonAreaMapper;
    @Autowired
    private GeoDriverRegionAreaMapper geoDriverRegionAreaMapper;
    @Autowired
    private GeoCustomerRegionAreaMapper geoCustomerRegionAreaMapper;
    @Autowired
    private OperationRecordHelper operationRecordHelper;
    @Autowired
    private AdvertiseSinglePicResourceRepository advertiseSinglePicResourceRepository;
    @Autowired
    private DriverRegionServiceArrangementMapper driverRegionServiceArrangementMapper;
    @Autowired
    private PrimaryCachePutter primaryCachePutter;

    @Value("${config.taxiAdvertiseStaticPageWxmina}")
    private String taxiAdvertiseStaticPageWxmina;
    @Value("${config.taxiAdvertiseStaticPageApp}")
    private String taxiAdvertiseStaticPageApp;


    /**
     * 广告列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<AdvertisePagePresenter>> advertiseDriverPage(AdminUser adminUser, AdvertiseWrapper wrapper) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        if (!identity.getType().equals(Enum.AccountType.platform)) {
            switch (adminUser.getAccountType()) {
                case company:
                case canton:
                    wrapper.setCantonIds(identity.getCantonIds());
            }
        }
        Page<AdvertisePagePresenter> advertisePagePresenterPage =
                advertiseMapper.advertisePage(wrapper);
        List<Long> cantionIds = advertisePagePresenterPage.getRecords().stream()
                .map(AdvertisePagePresenter::getCantonId)
                .collect(toList());
        if (ObjectUtils.isEmpty(cantionIds)) {
            return RestResult.success(advertisePagePresenterPage);
        }
        //区域
        QueryWrapper<GeoCanton> cantonWrapper = new QueryWrapper<>();
        cantonWrapper.select("id", "name");
        cantonWrapper.in("id", cantionIds);
        List<Map<String, Object>> geoCantons = geoCantonMapper.selectMaps(cantonWrapper);
        for (AdvertisePagePresenter a : advertisePagePresenterPage.getRecords()) {
            Long cantonId = a.getCantonId();
            //行政区信息
            for (Map c : geoCantons) {
                if (c.get("id").equals(cantonId)) {
                    a.setCantonName(String.valueOf(c.get("name")));
                    a.setCantonType("canton");
                    break;
                } else {
                    a.setCantonType("all");
                }
            }
        }
        return RestResult.success(advertisePagePresenterPage);
    }

    /**
     * 广告详情
     *
     * @param adminUser
     * @param id
     * @return
     */
    @Override
    public RestResult<AdvertiseDetailsPresenter> advertiseDetails(AdminUser adminUser, Long id) {
        AdvertiseDetailsPresenter advertiseDetailsPresenter = new AdvertiseDetailsPresenter();
        Advertise advertise = advertiseMapper.selectById(id);
        if (ObjectUtils.isEmpty(advertise)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        BeanUtils.copyProperties(advertise, advertiseDetailsPresenter);
        //是否在指定区域
        if (advertise.getCantonId() != 0) {
            advertiseDetailsPresenter.setCantonType("canton");
            advertiseDetailsPresenter.setSpecified_region(true);
        } else {
            advertiseDetailsPresenter.setCantonType("all");
            advertiseDetailsPresenter.setSpecified_region(false);
        }
        return RestResult.success(advertiseDetailsPresenter);
    }

    /**
     * 添加广告
     *
     * @param wrapper
     * @return
     */
    @Override
    public RestResult add(AdminUser adminUser, AdvertiseAddWrapper wrapper) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        Long cantonId = wrapper.getCantonId();
        if (!identity.getType().equals(Enum.AccountType.platform)) {
            switch (adminUser.getAccountType()) {
                case company:
                case canton:
                    if (identity.getCantonIds().indexOf(cantonId) == -1) {
                        return RestResult.failed("只能新增指定地区广告");
                    }
            }
        }
        Advertise advertise = new Advertise();
        AdvertiseApp app = wrapper.getApp();
        advertise.setApp(app);
        advertise.setRegionId(0L);
        advertise.setCityId(0);
        advertise.setCantonId(0L);
        //广告位 ,跳转方式 区分区分小程序
        switch (app) {
            case wxapp:
            case pointmarket:
                wrapper.setCategory(AdvertiseCategory.inappredirect);
                wrapper.setLocation(AdvertiseLocation.banner);
                break;
        }
        //是否一定区域内,并且核销小程序只能添加全地区
        if (wrapper.getSpecified_region() && app != AdvertiseApp.pointmarket) {
            //区域判断
            QueryWrapper<GeoCanton> cantonWrapper = new QueryWrapper<>();
            cantonWrapper.select("id", "name");
            cantonWrapper.in("id", cantonId);
            List<GeoCanton> geoCanton = geoCantonMapper.selectList(cantonWrapper);
            if (ObjectUtils.isEmpty(geoCanton)) {
                return RestResult.failed("所选地区不存在");
            }
            advertise.setCantonId(cantonId);
            //地区
            QueryWrapper<GeoCantonArea> geoCantonAreaQueryWrapper = new QueryWrapper<>();
            geoCantonAreaQueryWrapper.select("area_id");
            geoCantonAreaQueryWrapper.eq("canton_id", cantonId);
            List<GeoCantonArea> geoCantonAreas = geoCantonAreaMapper.selectList(geoCantonAreaQueryWrapper);
            Long areaId = geoCantonAreas.get(0).getAreaId();
            //设置运营区,区分司机和乘客,微信小程序的运营区取乘客数据
            switch (app) {
                case driverapp:
                    QueryWrapper<GeoDriverRegionArea> driverRegionAreaQueryWrapper = new QueryWrapper<>();
                    driverRegionAreaQueryWrapper.select("driver_region_id");
                    driverRegionAreaQueryWrapper.eq("area_id", areaId);
                    GeoDriverRegionArea geoDriverRegionArea = geoDriverRegionAreaMapper.selectOne(driverRegionAreaQueryWrapper);
                    if (!ObjectUtils.isEmpty(geoDriverRegionArea)) {
                        advertise.setRegionId(geoDriverRegionArea.getDriverRegionId());
                    }
                    break;
                default:
                    QueryWrapper<GeoCustomerRegionArea> customerRegionAreaQueryWrapper = new QueryWrapper<>();
                    customerRegionAreaQueryWrapper.select("customer_region_id");
                    customerRegionAreaQueryWrapper.eq("area_id", areaId);
                    GeoCustomerRegionArea geoCustomerRegionArea = geoCustomerRegionAreaMapper.selectOne(customerRegionAreaQueryWrapper);
                    if (!ObjectUtils.isEmpty(geoCustomerRegionArea)) {
                        advertise.setRegionId(geoCustomerRegionArea.getCustomerRegionId());
                    }
            }
            //设置城市id
            QueryWrapper<GeoArea> areaQueryWrapper = new QueryWrapper<>();
            areaQueryWrapper.select("city_id");
            areaQueryWrapper.eq("id", areaId);
            GeoArea geoArea = geoAreaMapper.selectOne(areaQueryWrapper);
            if (!ObjectUtils.isEmpty(geoArea)) {
                Long cityId = geoArea.getCityId();
                advertise.setCityId(Math.toIntExact(cityId));
            }
        }
        advertise.setCategory(wrapper.getCategory());
        advertise.setIsActive(wrapper.getIsActive());
        advertise.setLocation(wrapper.getLocation());
        advertise.setMediaUrl(wrapper.getMediaUrl());
        advertise.setPointTo(wrapper.getPointTo());
        advertise.setSortBy(wrapper.getSortBy());
        advertise.setTitle(wrapper.getTitle());

        advertiseMapper.insert(advertise);
        operationRecordHelper.addBusinessLog(String.format("新增了广告 [%d] 的标题为 %s 信息 ", advertise.getId(), wrapper.getTitle()));
        return RestResult.success();
    }

    /**
     * 修改广告
     *
     * @param adminUser
     * @param id
     * @param wrapper
     * @return
     */
    @Override
    public RestResult update(AdminUser adminUser, Long id, AdvertiseUpdateWrapper wrapper) {
        Advertise advertise = advertiseMapper.selectById(id);
        if (ObjectUtils.isEmpty(advertise)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        //判断平台是否包含此广告
        AdvertiseApp app = wrapper.getApp();
        AdvertiseApp advertiseApp = advertise.getApp();
        if (!app.equals(advertiseApp)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        Long cantonId = wrapper.getCantonId();
        Long advertiseCantonId = advertise.getCantonId();
        //判断地区广告
        if (!identity.getType().equals(Enum.AccountType.platform)) {
            switch (adminUser.getAccountType()) {
                case company:
                case canton:
                    if (identity.getCantonIds().indexOf(advertiseCantonId) == -1) {
                        return RestResult.failed("只能修改指定地区广告");
                    }
            }
        }
        //广告位 ,跳转方式 区分 小程序
        switch (app) {
            case wxapp:
            case pointmarket:
                wrapper.setCategory(AdvertiseCategory.inappredirect);
                wrapper.setLocation(AdvertiseLocation.banner);
        }
        //是否一定区域内
        if (wrapper.getSpecified_region() && app != AdvertiseApp.pointmarket) {
            //判断区域是否改变
            if (!cantonId.equals(advertiseCantonId)) {
                Advertise flag = new Advertise();
                QueryWrapper<GeoCanton> cantonWrapper = new QueryWrapper<>();
                cantonWrapper.select("id", "name");
                cantonWrapper.in("id", cantonId);
                List<GeoCanton> geoCanton = geoCantonMapper.selectList(cantonWrapper);
                if (ObjectUtils.isEmpty(geoCanton)) {
                    return RestResult.failed("所选地区不存在");
                }
                flag.setCantonId(cantonId);
                //地区
                QueryWrapper<GeoCantonArea> geoCantonAreaQueryWrapper = new QueryWrapper<>();
                geoCantonAreaQueryWrapper.select("area_id");
                geoCantonAreaQueryWrapper.eq("canton_id", cantonId);
                List<GeoCantonArea> geoCantonAreas = geoCantonAreaMapper.selectList(geoCantonAreaQueryWrapper);
                Long areaId = geoCantonAreas.get(0).getAreaId();
                //设置运营区,区分司机和乘客,微信小程序的运营区取乘客数据
                switch (app) {
                    case driverapp:
                        QueryWrapper<GeoDriverRegionArea> driverRegionAreaQueryWrapper = new QueryWrapper<>();
                        driverRegionAreaQueryWrapper.select("driver_region_id");
                        driverRegionAreaQueryWrapper.eq("area_id", areaId);
                        GeoDriverRegionArea geoDriverRegionArea = geoDriverRegionAreaMapper.selectOne(driverRegionAreaQueryWrapper);
                        if (!ObjectUtils.isEmpty(geoDriverRegionArea)) {
                            flag.setRegionId(geoDriverRegionArea.getDriverRegionId());
                        }
                        break;
                    default:
                        QueryWrapper<GeoCustomerRegionArea> customerRegionAreaQueryWrapper = new QueryWrapper<>();
                        customerRegionAreaQueryWrapper.select("customer_region_id");
                        customerRegionAreaQueryWrapper.eq("area_id", areaId);
                        GeoCustomerRegionArea geoCustomerRegionArea = geoCustomerRegionAreaMapper.selectOne(customerRegionAreaQueryWrapper);
                        if (!ObjectUtils.isEmpty(geoCustomerRegionArea)) {
                            flag.setRegionId(geoCustomerRegionArea.getCustomerRegionId());
                        }
                }
                //设置城市id
                QueryWrapper<GeoArea> areaQueryWrapper = new QueryWrapper<>();
                areaQueryWrapper.select("city_id");
                areaQueryWrapper.eq("id", areaId);
                GeoArea geoArea = geoAreaMapper.selectOne(areaQueryWrapper);
                if (!ObjectUtils.isEmpty(geoArea)) {
                    Long cityId = geoArea.getCityId();
                    flag.setCityId(Math.toIntExact(cityId));
                }
                new LambdaUpdateChainWrapper<>(advertiseMapper)
                        .eq(Advertise::getId, id)
                        .set(Advertise::getCantonId, cantonId)
                        .set(Advertise::getRegionId, flag.getRegionId())
                        .set(Advertise::getCityId, flag.getCityId())
                        .update();
            }
        } else {
            //全部区域下,行政区城市为0
            new LambdaUpdateChainWrapper<>(advertiseMapper)
                    .eq(Advertise::getId, id)
                    .set(Advertise::getCantonId, 0)
                    .set(Advertise::getRegionId, 0)
                    .set(Advertise::getCityId, 0)
                    .update();
        }
        new LambdaUpdateChainWrapper<>(advertiseMapper)
                .eq(Advertise::getId, id)
                .set(Advertise::getTitle, wrapper.getTitle())
                .set(Advertise::getMediaUrl, wrapper.getMediaUrl())
                .set(Advertise::getLocation, wrapper.getLocation())
                .set(Advertise::getPointTo, wrapper.getPointTo())
                .set(Advertise::getSortBy, wrapper.getSortBy())
                .set(Advertise::getIsActive, wrapper.getIsActive())
                .set(Advertise::getCategory, wrapper.getCategory())
                .set(Advertise::getUpdatedAt, new Date())
                .update();
        operationRecordHelper.addBusinessLog(String.format("修改了广告 [%d] 的信息 ", id));
        return RestResult.success();
    }

    /**
     * 批量修改(启用,禁用)
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult batchUpdateState(AdminUser adminUser, BatchUpdateStateWrapper wrapper) {
        AdvertiseApp app = wrapper.getApp();
        Boolean isActive = wrapper.getIsActive();
        List<Long> ids = wrapper.getIds();
        if (app.equals(AdvertiseApp.pointmarket)) {
            return RestResult.failed("核销小程序不能修改");
        }
        for (Long id : ids) {
            Advertise advertise = advertiseMapper.selectById(id);
            if (ObjectUtils.isEmpty(advertise)) {
                return RestResult.build(ResultEnum.NOT_FOUND);
            }
            if (!advertise.getApp().equals(app)) {
                return RestResult.build(ResultEnum.NOT_FOUND);
            }
        }
        new LambdaUpdateChainWrapper<>(advertiseMapper)
                .in(Advertise::getId, ids)
                .set(Advertise::getIsActive, isActive)
                .set(Advertise::getUpdatedAt, new Date())
                .update();
        operationRecordHelper.addBusinessLog(String.format("批量修改了广告 %s 的状态为 %s ", ids, isActive));
        return RestResult.success();
    }

    /**
     * 删除广告
     *
     * @param wrapper
     * @param adminUser
     * @return
     */
    @Override
    public RestResult delete(AdminUser adminUser, AdvertiseDeleteWrapper wrapper) {
        List<Long> ids = wrapper.getIds();
        for (Long id : ids) {
            Advertise advertise = advertiseMapper.selectById(id);
            if (ObjectUtils.isEmpty(advertise)) {
                return RestResult.build(ResultEnum.NOT_FOUND);
            }
            if (advertise.getApp().equals(AdvertiseApp.pointmarket)) {
                return RestResult.failed("核销小程序不能删除");
            }
            AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
            Long cantonId = advertise.getCantonId();
            switch (adminUser.getAccountType()) {
                case company:
                case canton:
                    if (identity.getCantonIds().indexOf(cantonId) == -1) {
                        return RestResult.failed("只能删除指定地区广告");
                    }
            }
            Boolean isActive = advertise.getIsActive();
            if (isActive) {
                return RestResult.failed("有广告处于启用状态,不能删除");
            }
            advertiseMapper.deleteById(id);
            operationRecordHelper.addBusinessLog(String.format("删除了广告 [%d] 的信息 ", id));
        }
        return RestResult.success();
    }


    /**
     * 跳转地址返回链接
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    @Transactional
    public RestResult<String> pointTo(AdminUser adminUser, AdvertisePointToWrapper wrapper) {
        String title = wrapper.getTitle();
        String mediaUrl = wrapper.getMediaUrl();
        AdvertiseSinglePicResourceMongo advertiseSinglePicResourceMongo = new AdvertiseSinglePicResourceMongo();
        advertiseSinglePicResourceMongo.setTitle(title);
        advertiseSinglePicResourceMongo.setPic_url(mediaUrl);
        log.info("开始插入mongo:advertise_single_pic_resource");
        advertiseSinglePicResourceRepository.insert(advertiseSinglePicResourceMongo);
        ObjectId id = advertiseSinglePicResourceMongo.getId();
        com.njtoyo.taxi.admin.library.common.Enum.AdvertiseApp app = wrapper.getApp();
        //跳转地址url
        String pointTo;
        //小程序，app
        //微信小程序
        String taxiAdvertiseStaticPageWxmina = this.taxiAdvertiseStaticPageWxmina;
        //APP
        String taxiAdvertiseStaticPageApp = this.taxiAdvertiseStaticPageApp;
        switch (app) {
            case wxapp:
                pointTo = taxiAdvertiseStaticPageWxmina + "/static/advertise/detail/single_pic.html?k=" + id;
                break;
            default:
                pointTo = taxiAdvertiseStaticPageApp + "/temp/ad_detail/single_pic/" + id;
                break;
        }
        return RestResult.success(pointTo);
    }

    @Override
    public RestResult upload(MultipartFile file) {
        String url = "";
        try {
            url = OssClient.uploadFile(file.getInputStream(), file.getOriginalFilename(),OssClient.OOS_BUCKET_NAME_CARAPPADV);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return RestResult.success(url);
    }

    @Override
    public RestResult addAuto(AdminUser adminUser, AdvertiseAutoAddWrapper wrapper) {
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        Long cantonId = wrapper.getCantonId();
        if (!identity.getType().equals(Enum.AccountType.platform)) {
            switch (adminUser.getAccountType()) {
                case company:
                case canton:
                    if (identity.getCantonIds().indexOf(cantonId) == -1) {
                        return RestResult.failed("只能新增指定地区广告");
                    }
            }
        }
        Advertise advertise = new Advertise();
        AdvertiseApp app = wrapper.getApp();
        advertise.setApp(app);
        advertise.setRegionId(0L);
        advertise.setCityId(0);
        advertise.setCantonId(0L);


        //是否一定区域内,并且核销小程序只能添加全地区
        if (wrapper.getSpecified_region()) {
            //区域判断
            QueryWrapper<GeoCanton> cantonWrapper = new QueryWrapper<>();
            cantonWrapper.select("id", "name");
            cantonWrapper.in("id", cantonId);
            List<GeoCanton> geoCanton = geoCantonMapper.selectList(cantonWrapper);
            if (ObjectUtils.isEmpty(geoCanton)) {
                return RestResult.failed("所选地区不存在");
            }
            advertise.setCantonId(cantonId);
            //地区
            QueryWrapper<GeoCantonArea> geoCantonAreaQueryWrapper = new QueryWrapper<>();
            geoCantonAreaQueryWrapper.select("area_id");
            geoCantonAreaQueryWrapper.eq("canton_id", cantonId);
            List<GeoCantonArea> geoCantonAreas = geoCantonAreaMapper.selectList(geoCantonAreaQueryWrapper);
            Long areaId = geoCantonAreas.get(0).getAreaId();
            //设置运营区,区分司机和乘客,微信小程序的运营区取乘客数据
            QueryWrapper<GeoDriverRegionArea> driverRegionAreaQueryWrapper = new QueryWrapper<>();
            driverRegionAreaQueryWrapper.select("driver_region_id");
            driverRegionAreaQueryWrapper.eq("area_id", areaId);
            GeoDriverRegionArea geoDriverRegionArea = geoDriverRegionAreaMapper.selectOne(driverRegionAreaQueryWrapper);
            if (!ObjectUtils.isEmpty(geoDriverRegionArea)) {
                advertise.setRegionId(geoDriverRegionArea.getDriverRegionId());
            }
            //设置城市id
            QueryWrapper<GeoArea> areaQueryWrapper = new QueryWrapper<>();
            areaQueryWrapper.select("city_id");
            areaQueryWrapper.eq("id", areaId);
            GeoArea geoArea = geoAreaMapper.selectOne(areaQueryWrapper);
            if (!ObjectUtils.isEmpty(geoArea)) {
                Long cityId = geoArea.getCityId();
                advertise.setCityId(Math.toIntExact(cityId));
            }
        }

        advertise.setCategory(wrapper.getCategory());
        advertise.setIsActive(wrapper.getIsActive());
        advertise.setLocation(wrapper.getLocation());
        advertise.setMediaUrl(wrapper.getMediaUrl());
        advertise.setPointTo(wrapper.getPointTo());
        advertise.setSortBy(wrapper.getSortBy());
        advertise.setTitle(wrapper.getTitle());
        advertise.setMediaType(wrapper.getMediaType());
        advertise.setMediaDuration(wrapper.getMediaDuration());
        advertise.setShowTimes(wrapper.getShowTimes());
        advertise.setAdShowAfter(wrapper.getAdShowAfter());
        advertise.setGapDuration(wrapper.getGapDuration());

        advertiseMapper.insert(advertise);
        operationRecordHelper.addBusinessLog(String.format("新增了广告 [%d] 的标题为 %s 信息 ", advertise.getId(), wrapper.getTitle()));
        return RestResult.success();
    }

    @Override
    public RestResult updateAuto(AdminUser adminUser, Long id, AdvertiseAutoAddWrapper wrapper) {
        Advertise advertise = advertiseMapper.selectById(id);
        if (ObjectUtils.isEmpty(advertise)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        //判断平台是否包含此广告
        AdvertiseApp app = wrapper.getApp();
        AdvertiseApp advertiseApp = advertise.getApp();
        if (!app.equals(advertiseApp)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        Long cantonId = wrapper.getCantonId();
        Long advertiseCantonId = advertise.getCantonId();
        //判断地区广告
        if (!identity.getType().equals(Enum.AccountType.platform)) {
            switch (adminUser.getAccountType()) {
                case company:
                case canton:
                    if (identity.getCantonIds().indexOf(advertiseCantonId) == -1) {
                        return RestResult.failed("只能修改指定地区广告");
                    }
            }
        }
        //是否一定区域内
        if (wrapper.getSpecified_region()) {
            //判断区域是否改变
            if (!cantonId.equals(advertiseCantonId)) {
                Advertise flag = new Advertise();
                QueryWrapper<GeoCanton> cantonWrapper = new QueryWrapper<>();
                cantonWrapper.select("id", "name");
                cantonWrapper.in("id", cantonId);
                List<GeoCanton> geoCanton = geoCantonMapper.selectList(cantonWrapper);
                if (ObjectUtils.isEmpty(geoCanton)) {
                    return RestResult.failed("所选地区不存在");
                }
                flag.setCantonId(cantonId);
                //地区
                QueryWrapper<GeoCantonArea> geoCantonAreaQueryWrapper = new QueryWrapper<>();
                geoCantonAreaQueryWrapper.select("area_id");
                geoCantonAreaQueryWrapper.eq("canton_id", cantonId);
                List<GeoCantonArea> geoCantonAreas = geoCantonAreaMapper.selectList(geoCantonAreaQueryWrapper);
                Long areaId = geoCantonAreas.get(0).getAreaId();
                //设置运营区,区分司机和乘客,微信小程序的运营区取乘客数据
                QueryWrapper<GeoDriverRegionArea> driverRegionAreaQueryWrapper = new QueryWrapper<>();
                driverRegionAreaQueryWrapper.select("driver_region_id");
                driverRegionAreaQueryWrapper.eq("area_id", areaId);
                GeoDriverRegionArea geoDriverRegionArea = geoDriverRegionAreaMapper.selectOne(driverRegionAreaQueryWrapper);
                if (!ObjectUtils.isEmpty(geoDriverRegionArea)) {
                    flag.setRegionId(geoDriverRegionArea.getDriverRegionId());
                }
                //设置城市id
                QueryWrapper<GeoArea> areaQueryWrapper = new QueryWrapper<>();
                areaQueryWrapper.select("city_id");
                areaQueryWrapper.eq("id", areaId);
                GeoArea geoArea = geoAreaMapper.selectOne(areaQueryWrapper);
                if (!ObjectUtils.isEmpty(geoArea)) {
                    Long cityId = geoArea.getCityId();
                    flag.setCityId(Math.toIntExact(cityId));
                }
                new LambdaUpdateChainWrapper<>(advertiseMapper)
                        .eq(Advertise::getId, id)
                        .set(Advertise::getCantonId, cantonId)
                        .set(Advertise::getRegionId, flag.getRegionId())
                        .set(Advertise::getCityId, flag.getCityId())
                        .update();
            }
        } else {
            //全部区域下,行政区城市为0
            new LambdaUpdateChainWrapper<>(advertiseMapper)
                    .eq(Advertise::getId, id)
                    .set(Advertise::getCantonId, 0)
                    .set(Advertise::getRegionId, 0)
                    .set(Advertise::getCityId, 0)
                    .update();
        }
        new LambdaUpdateChainWrapper<>(advertiseMapper)
                .eq(Advertise::getId, id)
                .set(Advertise::getTitle, wrapper.getTitle())
                .set(Advertise::getMediaUrl, wrapper.getMediaUrl())
                .set(Advertise::getLocation, wrapper.getLocation())
                .set(Advertise::getSortBy, wrapper.getSortBy())
                .set(Advertise::getIsActive, wrapper.getIsActive())
                .set(Advertise::getCategory, wrapper.getCategory())
                .set(Advertise::getMediaType, wrapper.getMediaType())
                .set(Advertise::getMediaDuration, wrapper.getMediaDuration())
                .set(Advertise::getAdShowAfter, wrapper.getAdShowAfter())
                .set(Advertise::getGapDuration, wrapper.getGapDuration())
                .set(Advertise::getShowTimes, wrapper.getShowTimes())
                .set(Advertise::getUpdatedAt, new Date())
                .update();
        operationRecordHelper.addBusinessLog(String.format("修改了广告 [%d] 的信息 ", id));
        return RestResult.success();
    }

    private RestResult getRegionByCantonId(Long cantonId) {
        if (cantonId == 0) {
            return RestResult.success(0L);
        }
        //区域判断
        QueryWrapper<GeoCanton> cantonWrapper = new QueryWrapper<>();
        cantonWrapper.select("id", "name");
        cantonWrapper.in("id", cantonId);
        List<GeoCanton> geoCanton = geoCantonMapper.selectList(cantonWrapper);
        if (ObjectUtils.isEmpty(geoCanton)) {
            return RestResult.failed("所选地区不存在");
        }
        Long regionId = null;
        //地区
        QueryWrapper<GeoCantonArea> geoCantonAreaQueryWrapper = new QueryWrapper<>();
        geoCantonAreaQueryWrapper.select("area_id");
        geoCantonAreaQueryWrapper.eq("canton_id", cantonId);
        List<GeoCantonArea> geoCantonAreas = geoCantonAreaMapper.selectList(geoCantonAreaQueryWrapper);
        Long areaId = geoCantonAreas.get(0).getAreaId();
        QueryWrapper<GeoDriverRegionArea> driverRegionAreaQueryWrapper = new QueryWrapper<>();
        driverRegionAreaQueryWrapper.select("driver_region_id");
        driverRegionAreaQueryWrapper.eq("area_id", areaId);
        GeoDriverRegionArea geoDriverRegionArea = geoDriverRegionAreaMapper.selectOne(driverRegionAreaQueryWrapper);
        if (!ObjectUtils.isEmpty(geoDriverRegionArea)) {
            regionId = geoDriverRegionArea.getDriverRegionId();
        }
        return RestResult.success(regionId);
    }

    @Override
    public RestResult getAutoTimes(Long cantonId) {
        RestResult res = getRegionByCantonId(cantonId);
        if (!res.isSuccess()) {
            return RestResult.failed(res.getMsg());
        }
        Long regionId = (Long) res.getData();
        DriverRegionServiceArrangement driverRegionServiceArrangement = driverRegionServiceArrangementMapper.selectOne(Wrappers.<DriverRegionServiceArrangement>lambdaQuery()
                .eq(DriverRegionServiceArrangement::getServiceCategory, DriverRegionServiceArrangementCategory.car_app_adv)
                .eq(DriverRegionServiceArrangement::getDriverRegionId, regionId));
        return RestResult.success(driverRegionServiceArrangement);
    }

    @Override
    public RestResult saveAutoTimes(Long cantonId, Integer times) {
        RestResult res = getRegionByCantonId(cantonId);
        if (!res.isSuccess()) {
            return RestResult.failed(res.getMsg());
        }
        Long regionId = (Long) res.getData();

        DriverRegionServiceArrangement driverRegionServiceArrangement = driverRegionServiceArrangementMapper.selectOne(Wrappers.<DriverRegionServiceArrangement>lambdaQuery()
                .eq(DriverRegionServiceArrangement::getServiceCategory, DriverRegionServiceArrangementCategory.car_app_adv)
                .eq(DriverRegionServiceArrangement::getDriverRegionId, regionId));
        if (ObjectUtil.isNotNull(driverRegionServiceArrangement)) {
            driverRegionServiceArrangement.setDetailSpecification(JSON.toJSONString(Dict.create().set("times", times)));
            driverRegionServiceArrangement.setUpdatedAt(DateUtil.date());
            driverRegionServiceArrangementMapper.updateById(driverRegionServiceArrangement);
        } else {
            DriverRegionServiceArrangement add = new DriverRegionServiceArrangement();
            add.setIsOpen(true);
            add.setServiceCategory(DriverRegionServiceArrangementCategory.car_app_adv);
            add.setDriverRegionId(regionId);
            add.setDetailSpecification(JSON.toJSONString(Dict.create().set("times", times)));
            add.setCreatedAt(DateUtil.date());
            driverRegionServiceArrangementMapper.insert(add);
        }
        primaryCachePutter.deleteDriverServiceArrangement();
        return RestResult.success();
    }


}
